// uploadFile.js

export default function uploadFile(config) {
      // 如果本地有数据，则需要携带token
      const mytoken = uni.getStorageSync('token');
      const urls = [];
      const errs = [];
      
      if (mytoken) {
        config.header = {
          "Authorization": mytoken
        };
      }
      
      // 封装上传单个文件的方法
      const up = (url) => {
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            header: config.header,
            url: 'http://localhost:8080/file/upload',
            filePath: url,
            name: 'file',
            formData: {},
            success(res) {
              urls.push(JSON.parse(res.data).data[0].url);
              resolve(1);
            },
            fail(err) {
              errs.push(err);
              reject(1);
            }
          });
        });
      };

      // #ifdef H5
      uni.chooseImage({
        success: (chooseImageRes) => {
			console.log(chooseImageRes)
          const tempFilePaths = chooseImageRes.tempFiles;
          let filearray = [];
          
		  for(let i=0; i<tempFilePaths.length; i++){
			  filearray.push({ name: 'file', file: tempFilePaths[i], uri: tempFilePaths[i].path });
		  }
          // console.log(filearray)
          uni.uploadFile({
            header: config.header,
            url: 'http://localhost:9999/api/file/upload',
            files: filearray,
            name: 'file',
            formData: {},
            success(res) {
              // JSON.parse(res.data).data.forEach(item => urls.push(item.url));
              // console.log(JSON.parse(res.data).data.url)
              if (typeof config.success === 'function') {
                config.success(JSON.parse(res.data).data.url);
              }
              
              // 重置状态
              urls.length = 0;
              errs.length = 0;
            },
            fail: (err) => {
              if (typeof config.fail === 'function') {
                config.fail(err);
              }
            }
          });
        }
      });
      // #endif
      
      // #ifdef MP-WEIXIN
      uni.chooseImage({
        success: async (res) => {
          const tempFilePaths = res.tempFilePaths;
          
          // 限制最多上传9张图片
          for (var i = 0; i < tempFilePaths.length && i < 9; i++) {
            await up(tempFilePaths[i]);
          }
          
          if (typeof config.success === 'function') {
            config.success(urls);
          }
          
          if (errs.length > 0 && typeof config.fail === 'function') {
            config.fail(errs);
          }
          
          // 重置状态
          urls.length = 0;
          errs.length = 0;
        }
      });
      // #endif
};